package com.work.formaldehyde.activity;

import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.wang.avi.AVLoadingIndicatorView;
import com.work.formaldehyde.R;
import com.work.formaldehyde.activityadapter.GouWuCheAdapter;
import com.work.formaldehyde.model.GouWuCheModel;
import com.work.formaldehyde.util.ApiUtils;
import com.work.formaldehyde.util.Url;
import com.yydcdut.sdlv.Menu;
import com.yydcdut.sdlv.MenuItem;
import com.yydcdut.sdlv.SlideAndDragListView;

import org.json.JSONObject;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class GouWuCheActivity extends Activity implements View.OnClickListener {

    private ImageView comeback;
    public static ImageView check_gouwuche;
    private RelativeLayout gouwuche_jiesuan;
    private LinearLayout all_check;
    private ListView gouwuche_check_list;
    private GouWuCheModel gouWuCheModel;
    public static TextView allmoney;
    private AVLoadingIndicatorView back_loding_avi;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ApiUtils.ActivityIsLogin(this, 1);
        setContentView(R.layout.activity_gouwuche);
        comeback = findViewById(R.id.jiance_comeback);
        comeback.setOnClickListener(this);
        back_loding_avi = findViewById(R.id.back_loding_avi);
        back_loding_avi.hide();
        if (ApiUtils.isNetworkConnected(GouWuCheActivity.this))
            init();
    }
    public static ArrayList<Integer> intary = new ArrayList<>();
    public static int gouwuchecheck = 0;
    public static int allcheck_bl = 0;
    public static int getlistsize = 0;
    public int indexs = 0;
    public boolean oks = false;

    /**
     * 初始加载
     */
    public void init() {
        allmoney = findViewById(R.id.allmoney);
        check_gouwuche = findViewById(R.id.check_gouwuche);
        all_check = findViewById(R.id.all_check);
        all_check.setOnClickListener(this);
        gouwuche_check_list = findViewById(R.id.gouwuche_check_list);
        Init();
        gouwuche_check_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                oks = true;
                windows(GouWuCheActivity.this, all_check, position);
                indexs = position;
                return false;
            }
        });
        gouwuche_check_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (!oks) {
                    if (new_list_views1.get(i).equals("2")) {
                        new_list_views1.set(i, "1");
                        money = Double.parseDouble(new_list_views.get(i).getGoods_discount_price()) * Double.parseDouble(intary.get(i) + "");
                        String sallmoneys = new DecimalFormat("0.00").format(moneyall);
                        moneyall = Double.parseDouble(sallmoneys);
                        moneyall = moneyall - money;
                        allmoneys = new DecimalFormat("0.00").format(moneyall);
                        allmoney.setText("¥" + allmoneys);
                    } else {
                        new_list_views1.set(i, "2");
                        money = Double.parseDouble(new_list_views.get(i).getGoods_discount_price()) * Double.parseDouble(intary.get(i) + "");
                        moneyall = moneyall + money;
                        allmoneys = new DecimalFormat("0.00").format(moneyall);
                        allmoney.setText("¥" + allmoneys);
                    }
                    if (allcheck_bl == 1)
                        for (int list = 0; list < new_list_views1.size(); list++) {
                            if (new_list_views1.get(list).equals("1")) {
                                allcheck_bl = 0;
                                check_gouwuche.setImageResource(R.mipmap.addnc);
                                break;
                            }
                        }
                    if (allcheck_bl == 0) {
                        if (new_list_views1.get(i).equals("2"))
                            getlistsize++;
                        else
                            getlistsize--;

                    }
                    if (getlistsize == new_list_views1.size()) {
                        allcheck_bl = 1;
                        check_gouwuche.setImageResource(R.mipmap.addc);
                    }
                    myAdapter.notifyDataSetChanged();
                }
            }
        });
        gouwuche_jiesuan = findViewById(R.id.gouwuche_jiesuan);
        gouwuche_jiesuan.setOnClickListener(this);
        okHttp_postFromParameters();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        intary.clear();
        gouwuchecheck = 0;
        allcheck_bl = 0;
        getlistsize = 0;
        new_list_views.clear();
        new_list_views1.clear();
        allmoneys="";
        moneyall=0;
    }

    public static ArrayList<GouWuCheModel.data> new_list_views = new ArrayList<>();
    public static ArrayList<String> new_list_views1 = new ArrayList<>();
    public static GouWuCheAdapter myAdapter;

    public static String allmoneys;


    private static PopupWindow popupWindows;

    public void windows(Context context, View v, final int is) {
        View popupwindowviews = null;
        popupwindowviews = LayoutInflater.from(context).inflate(
                R.layout.popup_isdel, null);
        RelativeLayout dangqian = popupwindowviews.findViewById(R.id.dangqian);
        dangqian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ApiUtils.windows(GouWuCheActivity.this, gouwuche_check_list, "删除中...");
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        ApiUtils.closepopup();
                    }
                }, 10000);
                okHttp_Del(is);
                popupWindows.dismiss();
            }
        });
        RelativeLayout jieshu = popupwindowviews.findViewById(R.id.jieshu);
        jieshu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindows.dismiss();
            }
        });
        popupWindows = new PopupWindow(popupwindowviews, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindows.setAnimationStyle(R.style.popwin_anim_style);
        popupWindows.setTouchable(true);
        popupWindows.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // TODO Auto-generated method stub
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        popupWindows.setFocusable(true);
        popupWindows.setOutsideTouchable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.4f;
        getWindow().setAttributes(lp);
        popupWindows.showAtLocation(v, Gravity.BOTTOM, 0, 0);
    }

    private void okHttp_Del(final int i) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request;
                    RequestBody formBody = new FormBody.Builder().add("uid", Url.USER_ID).add("logintoken", Url.LOGIN_TOKEN).add("num", "-" + GouWuCheAdapter.item_num).add("goodsid", new_list_views.get(i).getId())
                            .build();
                    ApiUtils.SetLog("num="+ GouWuCheAdapter.item_num);
                    request = new Request.Builder().url(Url.GOUWUCHEUP).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethotsd1.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public Handler gethotsd1 = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    ApiUtils.closepopup();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        allcheck_bl = 0;
                        check_gouwuche.setImageResource(R.mipmap.addnc);
                        for (int list = 0; list < new_list_views1.size(); list++) {
                            new_list_views1.set(list, "1");
                        }
                        getlistsize = 0;
                        moneyall = 0;
                        allmoneys = new DecimalFormat("0.00").format(moneyall);
                        allmoney.setText("¥" + allmoneys);
                        ApiUtils.SetToast(GouWuCheActivity.this, success_Object.getString("msg"));
                        okHttp_postFromParameters();
                    } else {
//                        gouwuche_numtext.setText(positions + "");
                        ApiUtils.SetToast(GouWuCheActivity.this, success_Object.getString("msg"));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * 初始加载视图
     */
    public void Init() {

    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    double money;
    public static double moneyall = 0;
    private int indexid = 0;
    private String getstr = "", getstrs = "";

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.jiance_comeback:
                onBackPressed();
                break;
            case R.id.gouwuche_jiesuan:
                if (gouwuchecheck > 0) {
                    indexid = 0;
                    getstr = "";
                    getstrs = "";
                    for (int is = 0; is < new_list_views1.size(); is++) {
                        if (new_list_views1.get(is).equals("2")) {
                            indexid++;
                            getstr = getstr + "," + new_list_views.get(is).getGoods_id();
                            getstrs = getstrs + "," + new_list_views.get(is).getGoods_num();
                        }
                    }
                    String sbstr = getstr.substring(1, getstr.length());
                    String sbstrs = getstrs.substring(1, getstrs.length());
                    Intent setwx = new Intent(GouWuCheActivity.this, GouWuCheJieSuanActivity.class);
                    setwx.putExtra("dingdan", "false");
                    setwx.putExtra("shangpingid", sbstr);
                    setwx.putExtra("shangpingnum", sbstrs);
                    setwx.putExtra("allmoney", allmoneys);
                    startActivity(setwx, ActivityOptions.makeSceneTransitionAnimation(GouWuCheActivity.this).toBundle());
                } else {
                    ApiUtils.SetToast(GouWuCheActivity.this, "请选择要结算的商品");
                }
                break;
            case R.id.all_check:
                if (new_list_views.size() > 0)
                    if (allcheck_bl == 0) {
                        money = 0;
                        moneyall = 0;
                        allcheck_bl = 1;
                        check_gouwuche.setImageResource(R.mipmap.addc);
                        for (int list = 0; list < new_list_views1.size(); list++) {
                            new_list_views1.set(list, "2");
                        }
                        getlistsize = new_list_views.size();
                        if (new_list_views.size() > 0) {
                            for (int moneys = 0; moneys < new_list_views.size(); moneys++) {
                                money = (Double.parseDouble(new_list_views.get(moneys).getGoods_discount_price()) * Double.parseDouble(intary.get(moneys) + ""));
                                moneyall = moneyall + money;
                                allmoneys = new DecimalFormat("0.00").format(moneyall);
                                allmoney.setText("¥" + allmoneys);
                            }
                        }
                        myAdapter.notifyDataSetChanged();
                    } else {
                        allcheck_bl = 0;
                        check_gouwuche.setImageResource(R.mipmap.addnc);
                        for (int list = 0; list < new_list_views1.size(); list++) {
                            new_list_views1.set(list, "1");
                        }
                        getlistsize = 0;
                        moneyall = 0;
                        allmoneys = new DecimalFormat("0.00").format(moneyall);
                        allmoney.setText("¥" + allmoneys);
                        myAdapter.notifyDataSetChanged();
                    }
                break;
        }
    }

    private void okHttp_postFromParameters() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
//                    RequestBody formBody = new FormBody.Builder().add("uid", Url.USER_ID)
//                            .build();
//                    Request request = new Request.Builder().url(Url.GETGOUWUCHE).post(formBody).build();
//                    okhttp3.Response response = okHttpClient.newCall(request).execute();
//                    String msg = response.body().string();
//                    Message message = new Message();
//                    message.obj = msg;
//                    gethot1.sendMessage(message);
                    Request request = new Request.Builder().get().url(Url.GETGOUWUCHES + "?uid=" + Url.USER_ID + "&logintoken=" + Url.LOGIN_TOKEN).build();
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                        }

                        @Override
                        public void onResponse(Call call, final Response response) {
                            try {
                                final String responseStr;
                                responseStr = response.body().string();
                                Message message = new Message();
                                message.obj = responseStr;
                                gethot1.sendMessage(message);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public Handler gethot1 = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    back_loding_avi.hide();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        gouWuCheModel = gson.fromJson(msg.obj.toString(),
                                GouWuCheModel.class);
                        if (new_list_views != null && gouWuCheModel.getData().size() > new_list_views.size() || new_list_views.size()>gouWuCheModel.getData().size() ) {
                            new_list_views.clear();
                            new_list_views1.clear();
                            new_list_views.addAll(gouWuCheModel.getData());
                            for (int list_index = 0; list_index < gouWuCheModel.getData().size(); list_index++) {
                                new_list_views1.add("1");
                                intary.add(Integer.parseInt(new_list_views.get(list_index).getGoods_num()));
                            }
                        }
                        myAdapter = new GouWuCheAdapter(new_list_views,
                                GouWuCheActivity.this, new_list_views1, intary, GouWuCheActivity.this);
                        gouwuche_check_list.setAdapter(myAdapter);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

}
